
import asyncio
import websockets
import logging
from typing import List
from aiohttp import web
import aiohttp_cors  # 导入CORS模块

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

# 服务器配置
START_PORT = 8887
SERVER_COUNT = 10
HOST = "0.0.0.0"
HTTP_PORT = 8990

servers: List[websockets.WebSocketServer] = []
http_server = None


# ------------------------------
# WebSocket 相关逻辑
# ------------------------------
async def handle_client(websocket: websockets.WebSocketServerProtocol, port: int):
    client_addr = websocket.remote_address
    logging.info(f"端口 {port} - 新客户端连接: {client_addr}")

    try:
        await websocket.send(f"欢迎连接 WebSocket 服务器（端口：{port}）！")
        async for message in websocket:
            logging.info(f"端口 {port} - 收到客户端 {client_addr} 消息: {message}")
            await websocket.send(f"服务器（端口 {port}）已收到：{message}")

    except websockets.exceptions.ConnectionClosed:
        logging.info(f"端口 {port} - 客户端 {client_addr} 主动断开连接")
    except Exception as e:
        logging.error(f"端口 {port} - 客户端 {client_addr} 连接异常: {str(e)}")
    finally:
        logging.info(f"端口 {port} - 客户端 {client_addr} 连接已关闭")


async def start_single_server(port: int):
    async with websockets.serve(
            lambda ws: handle_client(ws, port),
            host=HOST,
            port=port,
            ping_interval=30,
            ping_timeout=60
    ) as server:
        servers.append(server)
        logging.info(f"✅ WebSocket 服务器已启动 - 监听端口: {port}")
        await server.wait_closed()


async def http_index_handler(request: web.Request):
    """HTTP根路径处理器"""
    data = {
	    "total": 1,
	    "items": [
	        {
	            "asTool": "false",
	            "audio": "welcome.wav",
	            "audioInfo": "{\"format\":\"wav\"}",
	            "dance": "",
	            "desc": "这是一个欢迎动作",
	            "file": "welcome_motion.json",
	            "fileInfo": "{\"format\":\"json\"}",
	            "key": "F1",
	            "name": "欢迎",
	            "playAudio": "true",
	            "reset": "true",
	            "status": "true",
	            "text": "欢迎光临",
	            "time": "5",
	            "uid": "unique-motion-id-12345",
	            "weight": "0"
	        }
	    ]
	}
    print(f"----------data:{data}")
    return web.json_response({
        "code": 200,
        "data":data
    })




async def start_http_server():
    global http_server
    # 创建HTTP应用
    app = web.Application()

    # 配置CORS
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
            allow_credentials=True,
            expose_headers="*",
            allow_headers="*",
            allow_methods="*"  # 允许所有HTTP方法
        )
    })

    app.router.add_post('/g1edu_motion/queryMotion', http_index_handler)

    for route in list(app.router.routes()):
        cors.add(route)

    # 启动服务器
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, host=HOST, port=HTTP_PORT)
    await site.start()

    http_server = runner
    logging.info(f"✅ HTTP 服务器已启动 - 监听端口: {HTTP_PORT} (已配置CORS)")

    await asyncio.Event().wait()


# ------------------------------
# 主程序入口
# ------------------------------
async def main():
    # 创建WebSocket服务器任务
    ws_tasks = [
        asyncio.create_task(start_single_server(START_PORT + i))
        for i in range(SERVER_COUNT)
    ]

    # 创建HTTP服务器任务
    http_task = asyncio.create_task(start_http_server())

    # 等待所有任务完成
    await asyncio.gather(*ws_tasks, http_task)


if __name__ == "__main__":
    try:
        logging.info(f"开始启动 {SERVER_COUNT} 个 WebSocket 服务器和 1 个 HTTP 服务器...")
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("\n收到终止信号，正在关闭所有服务器...")
        # 关闭WebSocket服务器
        for server in servers:
            server.close()
        # 关闭HTTP服务器
        if http_server:
            asyncio.run(http_server.cleanup())
        logging.info("所有服务器已关闭")